Java String Comparision

    String Comparision

    Strings in Java can be changed using the content and the reference. You can use the string comparison for authentication, sorting and reference matching like criteria. You can compare the string using three methods-

    • Using equals() method
    • Using == operator
    • Using compareTo() method

    Using equals() method-

    This method will allow you to compare the original content of the string. You can check the string equality using the equals() method. There are two methods that are provided by the string class-

    • public boolean equals(Object another) it will compare this string to the specified object.
    • public boolean equalsIgnoreCase(String another) it will compare this String to another String, ignoring case.

    Example-

    class Simple{  
    
     public static void main(String args[]){  
    
       String s="Hello"; 
    
    String s1="welcome";
    
    String s2=new String ("Hello"); 
    
      
    
       System.out.println(s.equals(s1));
    
      System.out.println(s.equals(s2));
    
     }  
    
    } 

    Output-

    Java String Comparison Example

    Using == operator

    This operator allows you to compare the references but not he value.

    Example-

    class Simple{  
    
     public static void main(String args[]){  
    
       String s="Hello"; 
    
    String s1="Hello";
    
    String s2=new String ("Hello"); 
    
      
    
       System.out.println(s==s1);
    
      System.out.println(s==s2);
    
     }  
    
    } 

    Output-

    Java String Comparison example

    The s and s1 points to the same instance whereas s2 refers to the instance that is created in the heap memory and is different from the s and s1 variables.

    Using compareTo() method-

    This method will compare the string value lexicographically and it will return an integer value that specifies if the first string less than, equal to or greater than the second provided string.

    • s1 == s2 :0
    • s1 > s2   :positive value
    • s1 < s2   :negative value

    Example-

    class Simple{  
     public static void main(String args[]){  
    
       String s="Hello"; 
    
    String s1="Hello";
    
    String s2=new String ("Hello"); 
    
      
    
       System.out.println(s.compareTo(s1));
    
      System.out.println(s.compareTo(s2));
    
     }  
    
    } 

    Output-